<template>
  <div class="enterprise-manage">
    <!-- 顶部操作区 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加用户
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table 
      :data="tableData" 
      style="width: 100%"
      :height="600"
      border>
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="name" label="真实姓名" />
      <el-table-column prop="role" label="角色">
        <template #default="scope">
          <el-tag :type="scope.row.role === '管理员' ? 'danger' : 'primary'">
            {{ scope.row.role  ?? "超级管理员"}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="date_joined" label="注册时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'info'">
            {{ scope.row.is_active ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button 
            :type="scope.row.status ? 'warning' : 'success'"
            :icon="scope.row.status ? Lock : Unlock"
            circle
            @click="handleActivate(scope.row)"
            :title="scope.row.status ? '禁用' : '激活'"
          />
          <el-button 
            type="danger" 
            :icon="Delete"
            circle
            @click="handleDelete(scope.row)"
            title="删除"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
		@current-change="queryUserList"
      />
    </div>

    <!-- 添加用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加用户"
      width="800px"
    >
      <el-form :model="form" label-width="100px"  ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码"/>
        </el-form-item>

        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入真实姓名"/>
        </el-form-item>
        <el-form-item label="手机号" prop="tel">
          <el-input v-model="form.tel" placeholder="请输入手机号"/>
        </el-form-item>

        <el-form-item label="班级" prop="clazz">
          <el-select v-model="form.clazz" placeholder="请选择班级" style="width: 100%">
			<template v-for="clazz in clazzList">
				<el-option :label="clazz.name" :value="clazz.id" />
			</template>
          </el-select>
        </el-form-item>
      
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
			<template v-for="role in roleList">
				<el-option :label="role.name" :value="role.id" />
			</template>
          </el-select>

        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.is_active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Lock, Unlock, Delete, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// import { name } from 'element-plus/dist/locale/zh-cn';
import { layer } from 'vue3-layer';
import API from '@/api/index.js';

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
// 定义角色表格
const roleList = ref([])
// 定义班级表格
const clazzList = ref([])


// 用户数据
const tableData = ref([

]);

// 计算总数
total.value = tableData.value.length;

// // 表单校验规则
// const rules = {
//   username: [
//     { required: true, message: '请输入用户名', trigger: 'blur' },
//     { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
//   ],
//   realName: [
//     { required: true, message: '请输入真实姓名', trigger: 'blur' }
//   ],
//   role: [
//     { required: true, message: '请选择角色', trigger: 'change' }
//   ]
// };

// 对话框相关
const dialogVisible = ref(false);
const formRef = ref(null);
const form = ref({
  username: '',
  name: '',
  role: '',
  is_active: true,
  tel:"",
  password:"123456",
  clazz:""
});

// 进入页面查询数据
onMounted(() => {
    // 调用接口查询所有的角色和班级信息
	queryRolesAndClazzList();
	// 查询用户列表
	queryUserList();
})

const queryRolesAndClazzList = () => {
	API.getRoleAndClazzList().then(response => {
		roleList.value = response.roleList;
		clazzList.value = response.clazzList;
	})
}

// 分页查询当前页面所有用户信息
const queryUserList= () =>{
	// 
	API.getUserList(currentPage.value, pageSize.value).then(response =>{
		// 获取接口返回的数据的总条数，并赋值给total
		total.value = response.count
		// 获取当前页数据并赋值给tableData
		tableData.value = response.results
	})
}


// 添加激活/禁用函数
const handleActivate = (row) => {
  const action = row.status ? '禁用' : '激活';
  ElMessageBox.confirm(
    `确定要${action}该用户吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      row.status = !row.status;
      ElMessage.success(`${action}成功`);
    })
    .catch(() => {
      ElMessage.info('已取消操作');
    });
};

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      const index = tableData.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        tableData.value.splice(index, 1);
      }
      ElMessage.success('删除成功');
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

// 添加用户
const handleAdd = () => {
  form.value = {
    username: '',
    name: '',
    role: '',
    is_active: true,
    tel:"",
    password:"123456",
    clazz:""
  };
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async (formEl) => {
  if (!formEl) return;
  if (form.value.username === ""){
    layer.msg("用户名不允许为空"); return;
  }
  if (form.value.password === ''){
    layer.msg("密码不允许为空"); return;
  }
  if (form.value.name === ''){
    layer.msg("真实姓名不允许为空"); return;
  }
  if (form.value.tel === ''){
    layer.msg("手机号不允许为空"); return;
  }
  if (form.value.role === ''){
    layer.msg("角色不允许为空"); return;
  }
//   调用接口完成用户的添加
    API.saveUser({
  ...form.value,
  clazz: Number(form.value.clazz), // 转换为数字
  role: Number(form.value.role)    // 转换为数字
}).then(response =>{
		// 调用查询所有用户接口
		queryUserList();
		// tableData.value.push(response);
		ElMessage.success('添加成功');
		dialogVisible.value = false;
	})



};
</script>

<style scoped>
.enterprise-manage {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-button {
  margin-right: 10px;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
